//
//  LQHTMLController.m
//  LingQianZhu
//
//  Created by 谢英泽 on 2016/12/21.
//  Copyright © 2016年 谢英泽. All rights reserved.
//

#import "ZCHTMLController.h"
#import "ZCWebProgressView.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface ZCHTMLController ()<WKNavigationDelegate,WKUIDelegate>

//自定义导航栏
@property (nonatomic, strong) UIView *navBar;
//自定义导航栏标题
@property (nonatomic, strong) UILabel *navTitleLabel;
//自定义导航栏颜色
@property (nonatomic, strong) UIColor *naviColor;

@property (nonatomic, strong) WKWebView *wkWebView;
//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
//网页加载的类型33
@property(nonatomic,assign) kWebLoadType loadType;
//保存POST请求体
@property (nonatomic, copy) NSString *postData;

@property (nonatomic, copy) NSString *htmlTitle;
@property (nonatomic, copy) NSString *htmlURL;

@end

@implementation ZCHTMLController

#pragma mark -外部方法

- (void)setHTML:(kWebLoadType)loadType navColor:(UIColor *)naviColor arrowType:(kBackArrowType)arrowType Title:(NSString *)title url:(NSString *)url
{
    //初始化数据
    _loadType = loadType;
    _naviColor = naviColor;
    _arrowType = arrowType;
    self.htmlTitle = title;
    self.htmlURL = url;
}

#pragma mark - ********************生命周期********************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self configuration];
    
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
    [self autoLayoutForSubView];
    
    self.navTitleLabel.text = self.htmlTitle;
    self.progressView.progressTintColor = kCOLOR_tabBar;

    //开始加载请求
    [self loadWebViewURLType];
    
     [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"WXPay"];
    [self.wkWebView setNavigationDelegate:nil];
    [self.wkWebView setUIDelegate:nil];
}

//注意，观察的移除
-(void)dealloc{
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

#pragma mark - ********************配置信息********************

- (void)configuration
{
    self.view.backgroundColor = kCOLOR_tableView;
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    if (self.param.count > 0) {
        _loadType = [self.param[@"loadType"] intValue];
        _htmlTitle = self.param[@"title"];
        _htmlURL = self.param[@"url"];
        _notNeedAppend = [self.param[@"notNeedAppend"] boolValue];
    }
}

- (void)autoLayoutForSubView
{
    [self.navBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@64);
    }];
    
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.top.equalTo(@64);
    }];
}


#pragma mark - ********************基础方法********************

#pragma mark - 加载方式

- (void)loadWebViewURLType
{
    switch (self.loadType) {
        //加载网页
        case kWebLoadTypeloadWebURLString:{
            
            if ([self.htmlURL hasSuffix:@"="]) {
                if (!self.notNeedAppend) {
                    if (![[UnityTool shareInstance] isLogin]) return;
                    self.htmlURL = [NSString stringWithFormat:@"%@%@",self.htmlURL,[[UnityTool shareInstance] userId]];
                }
            }
            
            NSURL *url;
            if (self.htmlURL.length > 0) {
                url = [NSURL URLWithString:[self.htmlURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            }else{
                return;
            }
            
            NSString *tempURL = [url absoluteString];
            if (![tempURL containsString:@"http"]) {
                tempURL = [[[NetworkCenter shareInstance] getBaseURL] stringByAppendingString:tempURL];
            }
            
            url = [NSURL URLWithString:tempURL];
            
            //无网络处理
            if (![[NetworkCenter shareInstance] isConnectNetWork]) {
                url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"NoNetwork" ofType:@"html"]];
            }
            
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
            [self.wkWebView loadRequest:request];
            break;
        }
        //加载本地文件
        case kWebLoadTypeloadWebHTMLString:{
            [self loadHostPathURL:self.htmlURL];
            break;
        }
        //调用JS的POST方法
        case kWebLoadTypePOSTWebURLString:{
            [self loadHostPathURL:@"XFWKJSPOST"];
            break;
        }
    }
}

/**
 加载本地文件

 @param url 本地html文件名
 */
- (void)loadHostPathURL:(NSString *)url
{
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
    [self.wkWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}


/**
 调用JS发送POST请求
 */
- (void)postRequestWithJS
{
    // 拼装成调用JavaScript的字符串
    NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", self.htmlURL, self.postData];
    // 调用JS代码
    [self.wkWebView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
    }];
}

#pragma mark - ********************代理方法********************

#pragma mark ================ WKNavigationDelegate ================

//这个是网页加载完成，导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
}

//开始加载
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    //开始加载的时候，让加载进度条显示
    self.progressView.hidden = NO;
    
    NSString *url = webView.URL.absoluteString;
    if ([url hasPrefix:@"lqg://app"]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
}

//内容返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

//服务器请求跳转的时候调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}

//服务器开始请求的时候调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"页面加载超时");
}

//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    
}

//进度条
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    
}

#pragma mark ================ WKUIDelegate ================

// 获取js 里面的提示
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

// js 信息的交流
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// 交互。可输入的文本。
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}

//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

//拦截执行网页中的JS方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
}

#pragma mark - ********************响应事件********************

//返回按钮
- (void)clickBack:(UIButton *)sender
{
    if ([self.wkWebView canGoBack])
    {
        [self.wkWebView goBack];
        //if (self.notNeedAppend) {
            //[self.webView performSelector:@selector(reload) withObject:nil afterDelay:0.1];
        //}
    }
    else
    {
         [self closeClick];
    }
}

- (void)closeClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - ********************懒加载*********************

- (WKWebView *)wkWebView{
    if (!_wkWebView) {
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
        //允许视频播放
        Configuration.allowsAirPlayForMediaPlayback = YES;
        // 允许在线播放
        Configuration.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互，选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
        //[UserContentController addScriptMessageHandler:self name:@"WXPay"];
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        Configuration.userContentController = UserContentController;
        _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:Configuration];
        _wkWebView.backgroundColor = kCOLOR_tableView;
        // 设置代理
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
        //开启手势触摸
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
        [_wkWebView sizeToFit];
    }
    return _wkWebView;
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 64, self.view.bounds.size.width, 2);
        // 设置进度条的色彩
        [_progressView setTrackTintColor:kCOLOR_clear];
         _progressView.progressTintColor = [UIColor greenColor];
    }
    return _progressView;
}

- (UIView *)navBar
{
    if (!_navBar) {
        _navBar = [UIView new];
        
        _navBar.backgroundColor = _naviColor;
        self.navView.navBackButton.hidden = YES;
        
        UIImage *arrowImage;
        UIColor *backColor;
        
        if (_arrowType == kBackArrowTypeWhite) {
            arrowImage = [UIImage imageNamed:@"unity_leftItem"];
            backColor = kCOLOR_white;
        }else  if (_arrowType == kBackArrowTypeDark){
            arrowImage = [UIImage imageNamed:@"unity_leftItem"];
            backColor = KCOLOR_font_normal;
        }
        
       //返回图标
        UIImageView *arrowImageView = [UIImageView new];
        arrowImageView.image = arrowImage;
        [_navBar addSubview:arrowImageView];
        [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(kUI_MarginW));
            make.centerY.equalTo(@5);
            make.width.equalTo(@8);
            make.height.equalTo(@16);
        }];
        
        //返回按钮
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setButtonStyle:@"返回" titleColor:backColor titleFont:kFONT_mainFont(14.f) texrAlignment:NSTextAlignmentLeft];
        [backButton addTarget:self action:@selector(clickBack:) forControlEvents:UIControlEventTouchUpInside];
        [_navBar addSubview:backButton];
        [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(arrowImageView.mas_right).offset(5);
            make.centerY.equalTo(arrowImageView);
            make.width.height.equalTo(@40);
        }];
        
        //标题
        UILabel *navTitleLabel = [UILabel new];
        [navTitleLabel setLabelStyle:@"" textColor:backColor textFont:kFONT_mainFont(16.f) texrAlignment:NSTextAlignmentCenter];
        self.navTitleLabel = navTitleLabel;
        [_navBar addSubview:navTitleLabel];
        [navTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(@0);
            make.centerY.equalTo(@5);
            make.width.equalTo(@160);
            make.height.equalTo(@30);
        }];
    }
    return _navBar;
}

#pragma mark - ********************网络模型********************

@end
